"ui";
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.window.setStatusBarColor(android.graphics.Color.TRANSPARENT);
activity.window.getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

var startTime, forwardTime, lastTime, NTPClockOffset, NTPClockDelay;
var isNeedFlash, autoPay, autoSelectAll;
var window;
//时间工具类
var timeUtils = require('TimeUtils.js');

var color = "#00aaff";
ui.layout(
    <vertical>
        <linear id="appbar" orientation="vertical" h="90">
            <View h="40" w="*"/>
            <frame h="50">
                <img id="back" src="@drawable/ic_arrow_back_black_48dp" padding="12" tint="#ffffff" w="50" h="50" foreground="?selectableItemBackground"/>
                <text id="app_name" textSize="18sp" textStyle="bold" textColor="#ffffff" w="*" text="淘宝购物车秒提" h="50" gravity="center"/>
                <text id="app_ms" textSize="14sp" textColor="#ffffff" w="70" layout_gravity="right" text="说明" h="50" gravity="center" foreground="?selectableItemBackground"/>
            </frame>
        </linear>
        <ScrollView>
            <vertical padding="10">
                <text textSize="13sp" id="networkTest" textColor="red" margin="0 5" text="正在检测网络延迟..." />

                <horizontal layout_weight="1" margin="0 0 0 5">
                    <Switch textSize="15sp" textColor="black" id="isUseNetTime"  text="网络时间" checked="true" layout_weight="1" padding="0 0 5 0"/>
                    <Switch textSize="15sp" textColor="black" id="isNeedFlash"text="自动刷新"  checked="false" layout_weight="1" padding="5 0 0 0"/>
                </horizontal>
                <horizontal layout_weight="1" margin="0 0 0 5">
                    <Switch textSize="15sp" textColor="black" id="autoPay" text="自动支付" checked="false" layout_weight="1" padding="0 0 5 0"/>
                    <Switch textSize="15sp" textColor="black" id="autoSelectAll" text="自动全选"  checked="false" layout_weight="1" padding="5 0 0 0"/>
                </horizontal>

                <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E2E2E2'></horizontal>
                <horizontal >
                    <checkbox id="baseTime" text="倒计时    " w="auto"  h="40" gravity="center" textColor="black" textSize="15" />
                    <horizontal  h="40" layout_weight="1">
                        <text h="40" text="X：" gravity="center" textColor="black" textSize="15"/>
                        <input h="40" id="xp" text="360" hint="360" marginBottom="-6" textSize="15"  w="100" padding="10 0 0 0" layout_weight="1"/>
                        <text h="40" text=" , Y：" gravity="center" textColor="black" textSize="15" />
                        <input h="40" id="yp" text="1250" hint="1250" marginBottom="-6" textSize="15" w="100" padding="10 0 0 0" layout_weight="1"/>
                    </horizontal>
                </horizontal>
                <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E2E2E2'></horizontal>

                <text textSize="15sp" textColor="black" text="开始时间（年/月/日 时:分:秒）" />
                <horizontal h="50">
                    <input id="startTime" textSize="15sp" textColor="black" padding="10 0 0 0" h="50" inputType="datetime" hint="0" w="0" layout_weight="4" />
                    <button id="selectTimePicker" style="Widget.AppCompat.Button.Colored"  h="50" gravity="center" text="选择" w="0" layout_weight="1" />
                </horizontal>

                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="提前开始时间" w="auto" h="40" gravity="center"/>
                    <input id="forwardTime" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp"  text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>

                <horizontal h="40" id="flush_layout">
                    <text textSize="15sp" textColor="black" text="提前刷新时间" w="auto" h="40" gravity="center"/>
                    <input id="flushTime" textSize="15sp" textColor="black" inputType="number"  w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp" text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>
                {/* <text textSize="13sp" textColor="black" text="提交频率（毫秒）" />
                <horizontal>
                <input id="interval" textColor="gray" inputType="none" w="120" text="300"  />
                <text h="30" text=" 到 " gravity="top|left" textColor="black" textSize="16" />
                <input id="interval_end" textColor="gray" inputType="none" w="120" text="1000" />
                </horizontal> */}

                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="抢购持续时间"  w="auto" h="40" gravity="center"/>
                    <input id="lastTime" textSize="15sp" textColor="black" inputType="number"  text="" hint="20"  w="120" h="40" padding="10 0 0 0"/>
                    <text textSize="15sp"  textColor="black" text="秒" w="auto" h="40"/>
                </horizontal>
                <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E2E2E2'></horizontal>
                {/* <text textSize="13sp" textColor="black" text="重复提交次数" />
                <input id="re_count" textColor="gray" inputType="number" text="5" /> */}
                <vertical h="*" gravity="center">
                    <button id="runSrt" h="40" w="200" bg="#FFF43F3B" textColor="#ffffff"  text="开始运行"  marginTop="20" layout_gravity="center"/>
                    <button id="restore" h="40" w="200" bg="#FFF43F3B" textColor="#ffffff" text="重置"  marginTop="20" layout_gravity="center"/>
                </vertical>
                
            </vertical>
        </ScrollView>
    </vertical>
);
ui.appbar.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FFF43F3B", "#FFEC008C"]);
/**
 * 转换成系统支持的颜色
 * @param {颜色} color 
 */
function Color(color) {
    return android.graphics.Color.parseColor(color);
}

/**
 * 配置渐变色
 * @param {方向} orientation 
 * @param {颜色数组} color 
 */
function GradientDrawable(orientation, color) {
    var colors = [];
    color.forEach(color => colors.push(Color(color)));
    return new android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation[orientation], colors);
}

ui.back.on("click",function(){
    ui.finish();
});
//创建选项菜单(右上角)
// ui.emitter.on("create_options_menu", menu => {
//     menu.add("说明");
// });

//监听选项菜单点击
// ui.emitter.on("options_item_selected", (e, item) => {
//     switch (item.getTitle()) {
//         case "说明":
//             alert("说明", "如果是聚划算的商品，没到点是不能勾选的，所以一定要开启自动刷新勾选。点击运行，切换到手机淘宝的购物车界面等待完成抢购。");
//             break;
//     }
//     e.consumed = true;
// });


ui.app_ms.on("click",function(){
    alert("说明", "如果是聚划算的商品，没到点是不能勾选的，所以一定要开启自动刷新勾选。点击运行，切换到手机淘宝的购物车界面等待完成抢购。");
});
//显示倒计时浮窗
ui.baseTime.on("check", function (checked) {
    // 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
    if (checked) {
        timeThread = threads.start(function () {
            var clockOffset = 0;
            if (ui.isUseNetTime.isChecked()) {
                clockOffset = NTPClockOffset;
            }
            window = timeUtils.countDownTimeShow(ui.xp.text(), ui.yp.text(), ui.startTime.text(), ui.forwardTime.text(), clockOffset);
        });
    } else if (window) {
        window.close();
        timeThread.interrupt();
    }
});

//自动支付设置
ui.autoPay.on("check", function (checked) {
    if (checked) {
        alert("警告", "自动支付仅限于开启了免密支付的设备，脚本会自动点击立即付款，慎用，风险自担！为了您的财产安全，请不要随意透露支付密码！！！");
    }
});

//需要刷新
ui.isNeedFlash.on("check", function(checked){
    if(checked){
        ui.flush_layout.visibility = 0x0;
    }else{
        ui.flush_layout.visibility = 0x8;
    }
});

function restore() {
    storage.clear();
    threads.start(NTP.sync);
    setTimeout(initConfig, 500);
    // toast("参数已重置")
}

//重置参数
ui.restore.on("click", () => {
    restore();
});

//校验时间
ui.networkTest.on("click", () => {
    threads.start(function () {
        //重置时间
        threads.start(NTP.sync);
        //刷新延迟
        setTimeout(reflushNetTime, 500);
    });
});

function reflushNetTime() {
    NTPClockOffset = storage.get("NTPClockOffset", "0");
    NTPClockDelay = storage.get("NTPClockDelay", "0");
    if (!NTPClockOffset) {
        NTPClockOffset = 0;
    } else {
        NTPClockOffset = parseInt(NTPClockOffset.split("|")[0]);
    }
    if (NTPClockOffset < 0) {
        var offset_str = "慢了" + -NTPClockOffset + 'ms，'
    } else {
        offset_str = "快了" + NTPClockOffset + 'ms，'
    }
    //网络延迟数据显示
    ui.networkTest.setText("当前设备时间比平台" + offset_str + "网络延迟：" + NTPClockDelay + "ms");
}

// 获取默认开始时间
function getTime() {
    var fmt = "YYYY-MM-dd hh:mm:ss";
    var d = new Date();
    var hh = d.getHours();
    var mm = d.getMinutes();
    if (mm < 30) {
        mm = 30
    } else {
        hh += 1;
        mm = 0
    }
    var o = {
        "Y+": d.getYear() + 1900,
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": hh,
        "m+": mm,
        "s+": 0
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 4) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    fmt = fmt.replace(/-/g, '/');
    return fmt;
}

// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}


// 检测网络延迟和时间偏差
var NTP = {
    requiredResponses: 3,
    serverTimes: [],
    serverDelay: [],
    serverUrl: "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp",
    resyncTime: 0, // minutes
    sync: function () {
        var offset = storage.get("NTPClockOffset");
        if (offset) {
            try {
                var t = offset.split("|")[1];
                var d = NTP.fixTime() - parseInt(t, 10);
                if (d < (1000 * 60 * NTP.resyncTime)) {
                    return false;
                }
            } catch (e) {
            }
        }
        NTP.getServerTime();
    },
    getNow: function () {
        var date = new Date();
        return date.getTime();
    },
    parseServerResponse: function (data) {
        var NtpStartTime = storage.get("NtpStartTime");
        var NtpStopTime = NTP.getNow();
        var origtime = parseInt(data.data.t);
        var delay = ((NtpStopTime - NtpStartTime) / 2);
        var offset = NtpStopTime - origtime - delay;
        NTP.serverTimes.push(offset);
        NTP.serverDelay.push(delay);

        // 因为网络问题，需要多次获取偏移值，获取平均值
        if (NTP.serverTimes.length >= NTP.requiredResponses) {
            var sumOffset = 0;
            var sumDelay = 0;
            var i = 0;
            for (i = 0; i < NTP.serverTimes.length; i++) {
                sumOffset += NTP.serverTimes[i];
                sumDelay += NTP.serverDelay[i];
            }
            var averageOffset = Math.round(sumOffset / i);
            var averageDelay = Math.round(sumDelay / i);
            storage.put("NTPClockOffset", averageOffset + '|' + NTP.fixTime()); // 保存获得offset时的时间戳
            storage.put("NTPClockDelay", averageDelay); // 保存获得offset时的时间戳
        } else {
            NTP.getServerTime();
        }
    },
    getServerTime: function () {
        var NtpStartTime = NTP.getNow();
        storage.put("NtpStartTime", NtpStartTime);

        var res = http.get(NTP.serverUrl);
        if (res.statusCode !== 200) {
            toast("获取网络时间失败: " + res.statusCode + " " + res.statusMessage);
            return false;
        } else {
            NTP.parseServerResponse(res.body.json());
        }
    },
    fixTime: function (timeStamp) {
        if (!timeStamp) {
            timeStamp = NTP.getNow();
        }
        var offset = storage.get("NTPClockOffset");
        try {
            if (!offset) {
                offset = 0;
            } else {
                offset = offset.split("|")[0];
            }
            if (isNaN(parseInt(offset, 10))) {
                return timeStamp;
            }
            return timeStamp + parseInt(offset, 10);
        } catch (e) {
            return timeStamp;
        }
    }
};

// 初始化用户配置
// storage.clear();
var storage = storages.create("tb_cart_t");
threads.start(NTP.sync);
setTimeout(initConfig, 500);

function initConfig() {
    NTPClockOffset = storage.get("NTPClockOffset", "0");
    NTPClockDelay = storage.get("NTPClockDelay", "0");
    if (!NTPClockOffset) {
        NTPClockOffset = 0;
    } else {
        NTPClockOffset = parseInt(NTPClockOffset.split("|")[0]);
    }
    if (NTPClockOffset < 0) {
             var offset_str = "慢了" + -NTPClockOffset + 'ms，'
         } else {
             offset_str = "快了" + NTPClockOffset + 'ms，'
         }
    ui.networkTest.setText("当前设备时间比淘宝" + offset_str + "网络延迟：" + NTPClockDelay + "ms");
    ui.startTime.setText(getTime());
    ui.isUseNetTime.checked = storage.get("isUseNetTime", true);
    ui.autoPay.checked = storage.get("autoPay", false);
    ui.autoSelectAll.checked = storage.get("autoSelectAll", false);
    ui.forwardTime.setText(storage.get("forwardTime", "500").toString());
    ui.flushTime.setText(storage.get("flushTime", "1500").toString());

    if(ui.isNeedFlash.isChecked()){
        ui.flush_layout.visibility = 0x0;
    }else{
        ui.flush_layout.visibility = 0x8;
    }

    // ui.interval.setText(storage.get("interval", "500").toString());
    // ui.interval_end.setText(storage.get("interval_end", "999").toString());
    // ui.re_count.setText(storage.get("re_count","20").toString());
    ui.lastTime.setText(storage.get("lastTime", "20").toString());
}

// 检测时间字符串是否有效
function strDateTime(str) {
    var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    var r = str.match(reg);
    if (r == null) return false;
    var d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]);
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}

function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var ms = time.getMilliseconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s) + ":" + add00(ms);
}

// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    if (isUseNetTime) {
        return now - NTPClockOffset
    }
    return now
}

// 程序主要逻辑
ui.runSrt.click(function () {
    // todo 检查无障碍服务
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }

    //运行
    startTime = ui.startTime.getText().toString();
    isUseNetTime = ui.isUseNetTime.isChecked();
    isNeedFlash = ui.isNeedFlash.isChecked();
    autoPay = ui.autoPay.isChecked();
    autoSelectAll = ui.autoSelectAll.isChecked();
    forwardTime = parseInt(ui.forwardTime.getText());
    flushTime = parseInt(ui.flushTime.getText());
    // interval = parseInt(ui.interval.getText());
    // interval_end = parseInt(ui.interval_end.getText());
    // re_count = parseInt(ui.re_count.getText());
    lastTime = parseInt(ui.lastTime.getText());
    if (!strDateTime(startTime)) {
        ui.startTime.setError("请输入正确的日期");
        return;
    } else if (forwardTime > 1000) {
        ui.forwardTime.setError("请输入0-1000之间的值");
        return;
    }
    storage.put("isUseNetTime", isUseNetTime);
    storage.put("forwardTime", forwardTime);
    storage.put("flushTime", flushTime);
    // storage.put("interval", interval);
    // storage.put("interval_end", interval_end);
    // storage.put("re_count", re_count);
    storage.put("lastTime", lastTime);
    // retryTimes = Math.round(lastTime * 1000 / interval);

    if (ui.runSrt.getText().toString() === '开始运行') {
        // 一直保持屏幕常亮
        device.keepScreenOn();
        // threads.start(testThread);
        threads.start(main);
        ui.runSrt.setText('停止运行');
    } else {
        threads.shutDownAll();
        console.hide();
        device.cancelKeepingAwake();
        ui.runSrt.setText('开始运行');
    }
});

/**
 * 测试开启多线程操作
 */
function testThread(){
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();

    var startChecktime = new Date(Date.parse(startTime)).getTime();
    var endTime = new Date(startChecktime.valueOf() + lastTime * 1000).getTime();
    var startChecktimeFix = startChecktime - forwardTime;

    //生成随机时间戳 随机次数是持续抢购时间的1.5倍
    var t = parseInt((lastTime * 3)/2);
    var start = new Array();
    start[0] = startChecktimeFix;
    for(var i=1; i<t; i++){
        var rt = random(500, 999);
        start[i] = startChecktimeFix + rt;
    }
    var nextNum = 0;
    setInterval(function(){
        var nowTime = getNow();
        if(nowTime>=start[nextNum]){
            nextNum ++;
            if(nextNum+1>=t){
                console.log("结束抢购");
                device.cancelKeepingAwake();
                threads.shutDownAll();
            }



        }
    },500);
}

/**
 * 打开应用程序
 */
function startTb(){
    logInfo('准备打开淘宝');
    app.launch("com.taobao.taobao");
    //判断是否打开tb
    var count = 1;
    tbCar = setInterval(function(){
        if (id('tabs').exists()|| className("android.widget.TabWidget").exists()) {
            logInfo("启动成功, 请手动进入购物车！");
            clearInterval(tbCar);
        }
        count ++;
        if(count==60){
            logInfo("自动进入购物车失败，请手动点击！");
            clearInterval(tbCar);
        }
    },1000);
}

function main() {
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();
    console.setTitle("淘宝购物车");

    var carCount = 0;
    var notInCarCount = 0;
    var retryCount = 0;
    var dunCount = 0;
    var susses = 0;
    var loadding = 0;
    var notChecked = 0;
    var backCount = 0;

    logError("脚本开始运行，当前时间偏移: " + NTPClockOffset + " 网络延迟: " + NTPClockDelay);
    var startChecktime = new Date(Date.parse(startTime)).getTime();
    var endTime = new Date(startChecktime.valueOf() + lastTime * 1000).getTime();
    var startChecktimeFix = startChecktime - forwardTime;
    var startFlashTime = startChecktime - flushTime;

    logInfo("预期开始抢购时间为：" + formatDate(startChecktimeFix));

    threads.start(startTb);

    // 检测是否进入购物车
    x = setInterval(function () {
        var t = getNow();
        if (t < startChecktimeFix) {
            if (id("button_cart_charge").exists() || className("android.widget.TextView").text("全选").exists()) {
                if (carCount === 0) {
                    logCommon("已进入购物车，请检查需要抢购的商品是否已勾选，并设置好购买数量，脚本将自动结算");
                    carCount++;
                    notInCarCount = 0
                }

            } else {
                if (notInCarCount === 0) {
                    logCommon("未进入购物车，请前往");
                    carCount = 0;
                    notInCarCount++
                }
            }
        } else {
            not_in_car_count = 0;  // 购物车状态复位
            clearInterval(x)
        }

    }, 500);

    if (autoSelectAll) {
        var selectThread = threads.start(function () {
            //在新线程执行的代码
            while (true) {
                //自动勾选
                var selectAll = className("android.widget.CheckBox").desc("全选").enabled(true).checked(false).findOne();
                selectAll.click()
                logCommon("自动全选");
                sleep(100);
            }
        });
    }

    var sleepThread = threads.start(function () {
        //在新线程执行的代码
        // logCommon( "破盾");
        while (true) {
            logError("被盾了：" + textContains("休息会").findOne().text());
            var sleepScope = textContains("向右滑动验证").findOne().bounds();

            var sx = sleepScope.left + (sleepScope.bottom - sleepScope.top) / 2;
            var ex = sleepScope.right - (sleepScope.bottom - sleepScope.top) / 2;
            var y = sleepScope.top + (sleepScope.bottom - sleepScope.top) / 2;

            logCommon("开始滑动")
            randomSwipe(sx, y, ex, y);
            logCommon("滑动完成")
            sleep(100);
        }
    });

    var readThread = threads.start(function () {
        //在新线程执行的代码
        // logCommon( "破盾");
        while (true) {
            var readButton = textContains("我知道了").findOne();
            logError("堵车了，稍后再试：" + readButton.click());
            sleep(100);
        }
    });

    //生成随机时间戳 随机次数是持续抢购时间的1.5倍
    var t = parseInt((lastTime * 3)/2);
    var start = new Array();
    start[0] = startChecktimeFix;
    for(var i=1; i<t; i++){
        var rt = random(500, 999);
        start[i] = startChecktimeFix + rt;
    }

    var nextNum = 0;
    var fl = 400;
    var timeFlush = true;
    z = setInterval(function () {
        var nowTime = getNow();
        var found = false;
        if (isNeedFlash && timeFlush && nowTime >= startFlashTime && nowTime < endTime) {
            timeFlush = false;
            logCommon("开始提前刷新");
            dropDown(fl);
        }
        //准备循环计算时间是否到达，执行点击操作
        if(nowTime>=start[nextNum]){
            nextNum ++;
            if(nextNum+1>=t){
                logError("超出预定抢购次数，抢购结束");
                device.cancelKeepingAwake();
                clearInterval(z);
                threads.shutDownAll();
            }
            if (retryCount === 0) {
                logInfo("时间到，开始抢购");
            }

            // 如果在购物车页面且已勾选商品
            if (className("android.widget.TextView").textContains("结算(").exists()) {
                className("android.widget.TextView").textContains("结算(").findOne().click();
                notInCarCount = 0;
                found = true;
                logCommon("去结算");
                className("android.widget.TextView").text("提交订单").findOne().click();
            }

            // 如果加载中
            else if (className("android.widget.TextView").textContains("加载中").exists()) {
                if (loadding === 0) {
                    loadding = 1;
                    logCommon("加载中");
                }
                found = true;
            }

            // // 如果被盾了
            // else if (className("android.widget.TextView").text("我知道了").exists()) {
            //     className("android.widget.TextView").text("我知道了").findOne().click();
            //     found = true;
            //     dunCount++;
            //     logError("第" + dunCount + "次被盾，您还有机会，重试中...");
            // }

            // 如果已经卖完
            else if (className("android.widget.TextView").text("失效宝贝").exists() || className("android.widget.TextView").text("商品不能购买").exists()) {
                found = true;
                if(backCount == 0){
                    logCommon("首次商品失效，重试...");
                }
                if(nextNum>=10){
                    logError("商品失效了，抢购结束。");
                    device.cancelKeepingAwake();
                    clearInterval(z);
                    threads.shutDownAll();
                }
                if (backCount > 0) {
                    sleep(backCount * (backCount - 1) * (backCount - 1) * (backCount - 1) * (backCount - 1) * 500);
                }
                submitBack();
                backCount++;
            }

            // 如果在提交订单界面
            else if (className("android.widget.TextView").text("提交订单").exists()) {
                className("android.widget.TextView").text("提交订单").findOne().click();
                found = true;
                logInfo("提交订单");
            }

            // 抢购成功
            else if (className("android.widget.TextView").text("立即付款").exists()) {
                logError("抢购成功！请支付！");
                var payButton = text("立即付款").findOne();
                if (autoPay) {
                    payButton.parent().click();
                    logError("尝试支付...");
                }
                found = true;
                susses++;
                clearInterval(z);
                device.cancelKeepingAwake();
                threads.shutDownAll();
            }

            // 如果未勾选商品
            // else if (!timeFlush && className("android.widget.TextView").text("结算").exists()) {
            //     className("android.widget.TextView").text("结算").findOne().click();
            //     found = true;
            //     if (notChecked === 0) {
            //         notChecked = 1;
            //         logCommon("请勾选需要抢购的商品");
            //         dropDown(fl);
            //         // id("checkbox_charge").desc("全选").findOne().click();
            //         className("android.widget.CheckBox").desc("全选").enabled(true).checked(false).findOne().click();
            //     }
            // }

            // 如果都不是
            else if (notInCarCount === 0 && susses === 0 && found === false) {
                logCommon("未检测到相关页面，请前往购物车");
                notInCarCount++;
            }

            retryCount++

        } else if (nowTime >= endTime) {
            logError("超出预定抢购时长，抢购结束");
            device.cancelKeepingAwake();
            clearInterval(z);
            threads.shutDownAll();
        }

    }, 200);
}


/**
 * 下拉滑动
 * @param {*} duration  不能小于350ms
 */
function dropDown(duration) {
    var width = device.width;
    var height = device.height;
    var y1 = height / 2;
    var y2 = height * 3 / 4;
    var x1 = width / 2;
    var x2 = width / 2;
    // log(x1+"|"+y1+"|"+x2+"|"+y2)
    swipe(x1, y1, x2, y2, duration);
    logInfo("刷新");
}

/**
* 退出提交订单页面
*/
function submitBack() {
    id("btn_back").findOne().click()
    // logCommon("退出提交订单页：" + id("btn_back").findOne().click());
}


/**
 * 真人模拟滑动函数
 *
 * 传入值：起点终点坐标
 * 效果：模拟真人滑动
 */
function randomSwipe(sx, sy, ex, ey) {
    //设置随机滑动时长范围
    var timeMin = 1000
    var timeMax = 3000
    //设置控制点极限距离
    var leaveHeightLength = 500

    //根据偏差距离，应用不同的随机方式
    if (Math.abs(ex - sx) > Math.abs(ey - sy)) {
        var my = (sy + ey) / 2
        var y2 = my + random(0, leaveHeightLength)
        var y3 = my - random(0, leaveHeightLength)

        var lx = (sx - ex) / 3
        if (lx < 0) { lx = -lx }
        var x2 = sx + lx / 2 + random(0, lx)
        var x3 = sx + lx + lx / 2 + random(0, lx)
    } else {
        var mx = (sx + ex) / 2
        var y2 = mx + random(0, leaveHeightLength)
        var y3 = mx - random(0, leaveHeightLength)

        var ly = (sy - ey) / 3
        if (ly < 0) { ly = -ly }
        var y2 = sy + ly / 2 + random(0, ly)
        var y3 = sy + ly + ly / 2 + random(0, ly)
    }

    //获取运行轨迹，及参数
    var time = [0, random(timeMin, timeMax)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)

    // log("随机控制点A坐标：" + x2 + "," + y2)
    // log("随机控制点B坐标：" + x3 + "," + y3)
    // log("随机滑动时长：" + time[1])

    // log("time:"+time)
    // log("track:"+track)
    //滑动
    gestures(time.concat(track))
}



function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
        var ax, bx, cx;
        var ay, by, cy;
        var tSquared, tCubed;
        var result_x, result_y;

        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        var t = dt * i
        tSquared = t * t;
        tCubed = tSquared * t;
        result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        curve[i] = {
            x: result_x,
            y: result_y
        };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
        try {
            var j = (i < 100) ? i : (199 - i);
            xx = parseInt(curve[j].x)
            yy = parseInt(Math.abs(100 - curve[j].y))
        } catch (e) {
            break
        }
        array.push([xx, yy])
    }

    return array
}